// File Name: key_task.c
// Author: kukukukuku~
// Date: 2024-06-25

#include "./User/Key/inc/key_task.h"
#include "./User/Step_Motor/inc/step_motor_task.h"

TaskHandle_t taskHandleKey; //Key任务句柄

/**
 * @brief   Key任务
 * @param   arg:    任务参数
 * @retval  None
 * @note    None
*/
void task_key(void *arg)
{
    static uint8_t i;
    static StepMotorState stepMotorStateLast;
    
    while(1)
    {
        //按键扫描和处理
        key_scan(&key[KEY_UP_INDEX]);
        key_up_handle();
        key_scan(&key[KEY_LEFT_INDEX]);
        key_left_handle();
        key_scan(&key[KEY_DOWN_INDEX]);
        key_down_handle();
        key_scan(&key[KEY_RIGHT_INDEX]);
        key_right_handle();
        key_scan(&key[KEY_MID_INDEX]);
        key_mid_handle();
        
        //左键和右键都松开，Step_Motor停止
        if(key[KEY_LEFT_INDEX].state == KEY_STATE_RELEASE && key[KEY_RIGHT_INDEX].state == KEY_STATE_RELEASE)
        {
            stepMotorState = STEP_MOTOR_STOP;
        }
        
        //Step_Motor状态更新，给予信号量
        if(stepMotorStateLast != stepMotorState)
        {
            xSemaphoreGive(semaphBinStepMotor);
            
            stepMotorStateLast = stepMotorState;
        }
        
        //所有按键都处于松开状态时停止按键长按判断定时器
        for(i = 0; i < KEY_NUM; i++)
        {
            if(key[i].state != KEY_STATE_RELEASE)
            {
                break;
            }
        }
        if(i == KEY_NUM)
        {
            keyAllReleaseFlag = 1;
            tmr_counter_enable(KEY_TMR, FALSE);
        }
        
        vTaskDelay(10);
    }
}
